package com.github.livebase.util.http;

import android.text.TextUtils;
import android.util.ArrayMap;

import com.github.livebase.util.PairsUtil;
import com.github.livebase.util.StringKeyValuePairs;
import com.github.livebase.util.base.ArraysUtil;
import com.github.livebase.util.base.ObjectsUtil;

import java.util.Map;

/**
 * @ClassName URLParams
 * @description:
 * @author: biao532
 * @create: 2024-02-17 14:46
 * @Version 1.0
 **/
public class URLParams {
    public static Map<String, String> params(String query) {
        if (query.startsWith("?")) {
            query = query.substring(1);
        }
        String[] pairs = query.split("&");
        Map<String, String> map = new ArrayMap<>(pairs.length);
        ArraysUtil.foreach(pairs, (p) -> {
            PairsUtil.pairsInsertMap(map, p, "=");
        });
        return map;
    }

    public static<V> String toQuery(Map<String, V> params, ObjectsUtil.Converter<V, String> valueConverter) {
        return toQuery(params, (key)->key, valueConverter);
    }
    public static String toQuery(Map<String, String> params) {
        return toQuery(params, (val)->val);
    }
    public static<V> String toQuery(Map<String, V> params, ObjectsUtil.Converter<String, String> keyConverter, ObjectsUtil.Converter<V, String> valueConverter) {
        if (null == params || params.isEmpty()) {
            return ObjectsUtil.Empty.STRING;
        }
        StringBuilder query = new StringBuilder();
        for (String key : params.keySet()) {
            query.append('&');
            query.append(keyConverter.convert(key));
            query.append('=');
            String value = valueConverter.convert(params.get(key));
            if (!TextUtils.isEmpty(value)) {
                query.append(value);
            }
        }
        return "?" + query.substring(1);
    }
}
